package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;

/**
 * @author 虎哥
 */
@Service
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    public List<CategoryDTO> queryCategoryByParentId(Long pid) {
        // 创建Category对象，封装查询的条件，通用mapper会把这个对象中的非空字段作为查询条件
        Category record = new Category();
        record.setParentId(pid);

        // 执行查询
        List<Category> list = categoryMapper.select(record);

        // 非空判断
        if (CollectionUtils.isEmpty(list)) {
            // 没有查询到，返回404
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }

        // 转换DTO并且返回
        return BeanHelper.copyWithCollection(list, CategoryDTO.class);
    }

    public List<CategoryDTO> queryByIds(List<Long> ids) {
        List<Category> list = categoryMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(list)) {
            // 没有查询到，返回404
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        // 转换DTO并且返回
        return BeanHelper.copyWithCollection(list, CategoryDTO.class);
    }

    public List<CategoryDTO> queryCategoryLevels(Long id) {
        // 查询三级分类
        CategoryDTO c3 = queryById(id);
        // 查询二级分类
        CategoryDTO c2 = queryById(c3.getParentId());
        // 查询一级
        CategoryDTO c1 = queryById(c2.getParentId());
        // 封装为一个集合返回
        return Arrays.asList(c1, c2, c3);
    }

    public CategoryDTO queryById(Long id){
        Category category = categoryMapper.selectByPrimaryKey(id);
        if (category == null) {
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        return BeanHelper.copyProperties(category, CategoryDTO.class);
    }
}
